package com.zkthink.ceres.order.util;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.zkthink.ceres.order.dto.ShippingDTO;
import com.zkthink.ceres.order.dto.ShippingTrace;
import com.zkthink.ceres.order.util.pojo.*;
import lombok.Data;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Data
public class Kd100TrackQueryAPI {

    private String key;

    private String customer;

    private String secret;

    private String userId;

    private String queryUrl = "https://poll.kuaidi100.com/poll/query.do";

    public ShippingDTO getOrderTracesByJson(String expCode, String expNo){

        QueryTrackReq queryTrackReq = new QueryTrackReq();
        QueryTrackParam queryTrackParam = new QueryTrackParam();
        queryTrackParam.setCom(expCode);
        queryTrackParam.setNum(expNo);
        queryTrackReq.setParam(queryTrackParam);
        queryTrackReq.setCustomer(customer);
        queryTrackReq.setSign(DigestUtils.md5Hex(new Gson().toJson(queryTrackParam)+key+customer).toUpperCase());


        HttpResult httpResult = HttpUtils.doPost(queryUrl, queryTrackReq);

        if (httpResult.getStatus() == 200 && StringUtils.isNotBlank(httpResult.getBody())){
            QueryTrackResp queryTrackResp = JSON.parseObject(httpResult.getBody(), QueryTrackResp.class);
            ShippingDTO shippingDTO = new ShippingDTO();
            shippingDTO.setShipperCode(expCode);
            shippingDTO.setLogisticCode(expNo);
            if (queryTrackResp != null && queryTrackResp.getData() != null) {
                List<ShippingTrace> shippingTraceList = new ArrayList();
                for(QueryTrackData queryTrackData:queryTrackResp.getData()){
                    ShippingTrace trace = new ShippingTrace();
                    trace.setAcceptTime(queryTrackData.getTime());
                    trace.setAcceptStation(queryTrackData.getContext());
                    shippingTraceList.add(trace);
                }
                shippingDTO.setTraces(shippingTraceList);
                return shippingDTO;
            }
        }

        return new ShippingDTO();
    }


}
